#!/bin/bash

# AIDE Ubuntu 服务器部署修复脚本
# 解决 Python 3.12 distutils 和 SQLite3 编译问题

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}========================================"
echo -e "AIDE Ubuntu 服务器部署修复工具"
echo -e "=======================================${NC}"
echo ""

echo -e "${BLUE}🔍 检查系统环境...${NC}"
echo "操作系统: $(lsb_release -d | cut -f2)"
echo "Python 版本: $(python3 --version)"
echo "Node.js 版本: $(node --version 2>/dev/null || echo '未安装')"
echo "Docker 版本: $(docker --version)"
echo "Docker Compose 版本: $(docker-compose --version)"
echo ""

# 检查是否在正确的目录
if [ ! -f "docker-compose.prod.yml" ]; then
    echo -e "${RED}❌ 错误: 请在项目根目录运行此脚本${NC}"
    exit 1
fi

echo -e "${BLUE}📁 创建必要的数据目录...${NC}"
# 创建数据持久化目录
sudo mkdir -p /var/lib/aide/postgres
sudo mkdir -p /var/lib/aide/redis
sudo chown -R 999:999 /var/lib/aide/postgres  # PostgreSQL 容器用户ID
sudo chown -R 999:999 /var/lib/aide/redis     # Redis 容器用户ID

# 创建本地目录
mkdir -p ./database/backup
mkdir -p ./backend/uploads
mkdir -p ./logs
mkdir -p ./nginx/logs
mkdir -p ./ssl

echo -e "${BLUE}🧹 清理 Docker 构建缓存...${NC}"
# 清理 Docker 构建缓存和悬空镜像
docker system prune -f
docker builder prune -f

echo -e "${BLUE}🔄 重新构建镜像...${NC}"

# 检测是否有 .env.prod 文件
if [ ! -f ".env.prod" ]; then
    echo -e "${YELLOW}⚠️ .env.prod 文件不存在，从模板创建...${NC}"
    cp env-prod-template.txt .env.prod
    echo -e "${YELLOW}📝 请编辑 .env.prod 文件，设置正确的配置值${NC}"
    echo "   nano .env.prod"
    echo ""
    read -p "配置完成后按 Enter 继续..."
fi

# 强制重新构建所有服务
echo -e "${BLUE}🚀 启动服务...${NC}"
docker-compose -f docker-compose.prod.yml -f docker-compose.linux.yml --env-file .env.prod down
docker-compose -f docker-compose.prod.yml -f docker-compose.linux.yml --env-file .env.prod build --no-cache
docker-compose -f docker-compose.prod.yml -f docker-compose.linux.yml --env-file .env.prod up -d

echo -e "${BLUE}⏳ 等待服务启动...${NC}"
sleep 30

echo -e "${BLUE}🔍 检查服务状态...${NC}"
docker-compose -f docker-compose.prod.yml -f docker-compose.linux.yml ps

echo ""
echo -e "${BLUE}📊 服务健康检查...${NC}"

# 检查各服务状态
services=("aide-postgres-prod" "aide-redis-prod" "aide-backend-prod" "aide-frontend-prod")
all_healthy=true

for service in "${services[@]}"; do
    if docker ps --filter "name=$service" --filter "status=running" --format "table {{.Names}}" | grep -q "$service"; then
        echo -e "✅ $service: ${GREEN}运行中${NC}"
        
        # 检查健康状态
        health=$(docker inspect --format='{{.State.Health.Status}}' "$service" 2>/dev/null || echo "no-healthcheck")
        if [ "$health" = "healthy" ]; then
            echo -e "   健康状态: ${GREEN}健康${NC}"
        elif [ "$health" = "unhealthy" ]; then
            echo -e "   健康状态: ${RED}不健康${NC}"
            all_healthy=false
        elif [ "$health" = "starting" ]; then
            echo -e "   健康状态: ${YELLOW}启动中${NC}"
        else
            echo -e "   健康状态: ${YELLOW}无健康检查${NC}"
        fi
    else
        echo -e "❌ $service: ${RED}未运行${NC}"
        all_healthy=false
    fi
done

echo ""
if [ "$all_healthy" = true ]; then
    echo -e "${GREEN}🎉 所有服务已成功启动！${NC}"
    echo ""
    echo -e "${BLUE}📋 访问信息:${NC}"
    echo "   前端: http://$(hostname -I | awk '{print $1}'):3000"
    echo "   后端 API: http://$(hostname -I | awk '{print $1}'):5000"
    echo ""
    echo -e "${BLUE}🔧 管理命令:${NC}"
    echo "   查看日志: docker-compose -f docker-compose.prod.yml -f docker-compose.linux.yml logs -f [service_name]"
    echo "   重启服务: docker-compose -f docker-compose.prod.yml -f docker-compose.linux.yml restart [service_name]"
    echo "   停止服务: docker-compose -f docker-compose.prod.yml -f docker-compose.linux.yml down"
else
    echo -e "${YELLOW}⚠️ 部分服务可能存在问题，请检查日志${NC}"
    echo ""
    echo -e "${BLUE}🔍 查看问题服务日志:${NC}"
    for service in "${services[@]}"; do
        if ! docker ps --filter "name=$service" --filter "status=running" --format "table {{.Names}}" | grep -q "$service"; then
            echo -e "${YELLOW}📄 $service 日志:${NC}"
            docker logs --tail 20 "$service" 2>/dev/null || echo "无法获取日志"
            echo ""
        fi
    done
fi

echo ""
echo -e "${BLUE}========================================"
echo -e "部署完成"
echo -e "=======================================${NC}"
